package com.hontlong.boy;

import java.io.IOException;
import java.sql.Connection;
import java.util.Iterator;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.log4j.Logger;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hit;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

import com.hontlong.boy.lucene.DBConnectFactory;
import com.hontlong.segment.analysis.MyAnalyzer;
import com.hontlong.segment.dictionary.Dictionary;

public class LuceneBoy extends Boy {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LuceneBoy.class);
	// 类的懒惰单态
	private static IndexSearcher searcher;
	private MyAnalyzer analyzer = new MyAnalyzer(Dictionary.getInstance(
			"../segment/dic_h/dic_m.txt", "utf-8"));

	public LuceneBoy() {
		this.name = "禄神小男孩";
		if (LuceneBoy.searcher == null) {
			synchronized (LuceneBoy.class) {
				IndexSearcher temp = LuceneBoy.searcher;
				if (temp == null) {
					synchronized (LuceneBoy.class) {
						try {
							temp = new IndexSearcher("./index");
						} catch (final CorruptIndexException e) {
							throw new RuntimeException(e);
						} catch (final IOException e) {
							throw new RuntimeException(e);
						}
					}
				}
				LuceneBoy.searcher = temp;
			}
		}
	}

	@Override
	public String talk(final String talk) {
		String r = "系统出错";
		try {
			final QueryParser parser = new QueryParser("askTitle",
					this.analyzer);
			final Query q = parser.parse(talk);
			final Hits hs = LuceneBoy.searcher.search(q);
			final Iterator<?> it = hs.iterator();
			if (!it.hasNext()) {
				LuceneBoy.logger.warn("没有搜索到对话[" + talk + "]");
				r = "我不知道你说的意思";
				return r;
			}
			final Hit h = (Hit) it.next();
			final String sid = h.get("id");
			final int id = Integer.parseInt(sid);

			final QueryRunner run = new QueryRunner();
			final Connection conn = DBConnectFactory.getDBConnection("boy");
			final Object[] objs = (Object[]) run.query(conn,
					"select id,answer,score from t_answer where askId=" + id
							+ " order by score limit 1 ", new ArrayHandler());
			conn.close();
			if ((objs == null) || (objs[1] == null)) {
				LuceneBoy.logger.warn("没有检索到askId[" + id + "]");
				r = "我不知道你说的意思";
				return r;
			}
			final String answer = (String) objs[1];
			r = answer;
		} catch (final Exception e) {
			LuceneBoy.logger.error("", e);
		}
		return r;
	}
}
